module triangle_mod

use point_mod

implicit none

type TriangleObj
    type(PointObj) :: pt1
    type(PointObj) :: pt2
    type(PointObj) :: pt3
    real :: area = 0.0
end type

interface Triangle
    module procedure Triangle_CreateFromPoints
end interface

contains

type(TriangleObj) function Triangle_CreateFromPoints(pt1, pt2, pt3) result(tri)
    type(PointObj), intent(in) :: pt1 !< first point of triangle
    type(PointObj), intent(in) :: pt2 !< second point of triangle
    type(PointObj), intent(in) :: pt3 !< third point of triangle
    tri%pt1 = pt1
    tri%pt2 = pt2
    tri%pt3 = pt3
    tri%area = Triangle_Area(tri)
end function Triangle_CreateFromPoints

real function Triangle_Area(tri) result(T)
    type(TriangleObj), intent(in) :: tri
    real :: a, b, c, s
    ! Using Heron's formula
    a = Point_Distance(tri%pt1, tri%pt2)
    b = Point_Distance(tri%pt2, tri%pt3)
    c = Point_Distance(tri%pt3, tri%pt1)
    s = 0.5*(a+b+c)
    T = (s-a)*(s-b)*(s-c)*s
    T = sqrt(T)
end function Triangle_Area


end module triangle_mod
